package com.lqk.demo.pessimisticlock.syncmode.sequencecontrol.fixedoperatesequence;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 固定运行顺序：ReentrantLock
 * @author lqk
 * @date 2021/12/23 16:20
 */
@Slf4j
public class TestReentrantLock {
    static ReentrantLock lock = new ReentrantLock();
    // 等烟的休息室
    static Condition t2wait= lock.newCondition();
    // 表示t1是否运行过
    static boolean t1runned = false;
    public static void main(String[] args) {

        Thread t1 = new Thread(() -> {
            lock.lock();
            try{
                log.debug("1");
                t1runned = true;
                t2wait.signalAll();
            }finally {
                lock.unlock();
            }
        }, "t1");

        Thread t2 = new Thread(() -> {
            lock.lock();
            try{
                while (!t1runned){
                    try {
                        t2wait.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                log.debug("2");
            }finally {
                lock.unlock();
            }
        }, "t2");

        t1.start();
        t2.start();
    }
}
